package plugins.search;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.form.ShowType;
import kd.bos.form.control.Search;
import kd.bos.form.control.events.SearchEnterEvent;
import kd.bos.form.control.events.SearchEnterListener;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

import java.util.*;

public class SearchPage extends AbstractFormPlugin implements SearchEnterListener {

    // 搜索控件标识
    @Override
    public void registerListener(EventObject e) {
        // 侦听搜索控件的搜索事件
        Search search = this.getControl("dcb4_searchap");
        search.addEnterListener(this);

    }

    @Override
    public void search(SearchEnterEvent evt) {
        Search search = (Search) evt.getSource();
        if (StringUtils.equals("dcb4_searchap", search.getKey())){
            String searchText = evt.getText();
            this.doSearch(searchText);          // 35行
        }
    }

    private void doSearch(String searchText) {
        ListShowParameter lsp = new ListShowParameter();
        lsp.setFormId("bos_list");
        lsp.setBillFormId("dcb4_dishes");
        lsp.getOpenStyle().setShowType(ShowType.Modal);
        ListFilterParameter filter = new ListFilterParameter();
        QFilter qFilter = new QFilter("name", QCP.like, "%" + searchText + "%");
        filter.setFilter(qFilter);         // 46行
        lsp.setListFilterParameter(filter);
        this.getView().showForm(lsp);



    }


    public List<String> getSearchList(SearchEnterEvent evt) {
        // 自动补全风格 输入搜索条件后 进入该方法组织数据返回前端显示
        Search search = (Search) evt.getSource();

        if (StringUtils.equals("dcb4_searchap", search.getKey())) {
            // 获取搜索条件
            String searchText = evt.getText();
            if (StringUtils.isNotBlank(searchText)) {
                return doSearchList(searchText);
            }

        }

        return null;
    }

    private List<String> doSearchList(String searchText) {

        String fields = "name";
        Map<String, String> searchList = new HashMap<String, String>();

        QFilter[] filters = new QFilter[] {
                new QFilter("name", QCP.like, "%" + searchText + "%")
        };

        // 查询数据
        DynamicObject[] objects = BusinessDataServiceHelper.load("dcb4_dishes", fields, filters);

        for (DynamicObject obj : objects) {
            String name = obj.getString("name");
            if (StringUtils.isNotBlank(name)) {
                searchList.put("dcb4_dishes" + " " + obj.get("id").toString(), name);
            }
        }

        return new ArrayList<>(searchList.values());
    }

}